package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"shops/cache"
	"shops/models"
	pkg2 "shops/pkg"

	"shops/shoprpc/internal/svc"
	"shops/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *shoprpc.RegisterRequest) (*shoprpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	models.DB.Where("account=?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("手机号重复,请重新注册")
	}
	if in.Account == "" || in.Password == "" {
		return nil, errors.New("手机号和密码不能为空")
	}
	if in.CaptchaCode == "" {
		return nil, errors.New("验证码不能为空")
	}
	cachejson, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if in.CaptchaCode != cachejson {
		return nil, errors.New("图形验证码错误，请重新输入")
	}
	data, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Account).Result()
	if in.SendSmsCode != data {
		return nil, errors.New("短信验证码错误，请重新输入")
	}
	user = models.User{
		Model:    gorm.Model{},
		Account:  in.Account,
		Password: pkg2.Md5Str(in.Password),
	}
	err := models.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &shoprpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
